package com.teamsun.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.teamsun.datasource.DatasourceHolder;
import com.teamsun.entity.DBCfg;
import com.teamsun.entity.RptResult;
import com.teamsun.entity.TableHeader;
import com.teamsun.mapper.DBCfgMapper;
import com.teamsun.mapper.ShowRptInfoMapper;
import com.teamsun.rptcfg.BaseRpt;
import com.teamsun.rptcfg.BaseRptColumn;
import com.teamsun.rptsql.DynamicSQL;
import com.teamsun.util.CacheUtil;
import com.teamsun.util.CommonUtils;
import com.teamsun.util.Constants;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.*;
import java.text.DecimalFormat;
import java.util.*;

/**
 * 文件上传下载服务
 */
public class DownloadServiceImpl implements IDownloadService {

    private static final Logger LOGGER = Logger.getLogger(DownloadServiceImpl.class);

    @Autowired
    private IShowRptService showRptService;

    /**
     * 查询待下载的数据
     * 由于根据dubbo协议传输数据，数据大小有限制
     * 所以当待下载的数据量大于5000条时，将数据缓存分批传给前台
     * @param baseRpt  报表信息
     * @param params  查询参数
     * @param key 数据缓存Key
     * @return
     */
    @Override
    public RptResult queryDownloadData(BaseRpt baseRpt, Map<String, String> params, String key) throws Exception {
        RptResult rptResult = showRptService.queryRptInfo(baseRpt, params);
        int totalCount = rptResult.getTotalCount();  // 总数据量
        List<Map<String, Object>> dataList = rptResult.getResultList();

        // 当数据量大于5000条时，缓存数据，分批传给前台
        if(totalCount > Constants.BATCH_CNT) {
            rptResult.setResultList(new ArrayList<Map<String, Object>>());
            CacheUtil.cacheMap.put(key, dataList);
            return rptResult;
        } else {
            return rptResult;
        }
    }

    /**
     * 从缓存缓存获取数据
     * @param key 缓存key
     * @param start 启示数据
     * @param end  结束数据
     * @return
     */
    @Override
    public List<Map<String, Object>> queyrDataFromCache(String key, int start, int end) {
        List<Map<String, Object>> cacheList = CacheUtil.getCacheList(key, start, end);

        return cacheList;
    }

    /**
     * 数据下载完后，需清除缓存
     * @param key
     */
    @Override
    public void deleteCache(String key) {
        CacheUtil.deleteListByKey(key);
    }
}
